from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import Users
from datetime import datetime
from PIL import Image
import time,os

# Create your views here.

def index(request):
	#return HttpResponse("Hello Python!")
	return render(request,"myapp/index.html")

def indexUsers(request):
	#return HttpResponse("Http")
	#获取用户信息
	list = Users.objects.all()
	context = {"userslist":list} #将信息封装到字典中
	return render(request,"myapp/Users/index.html",context) #加载信息并传递模板

def addUsers(request):
	return render(request,"myapp/Users/add.html")

def insertUsers(request):
	#获取并封装用户信息
	#try:
		#user = Users()
		#user.name = request.POST['name']
		#user.age = request.POST['age']
		#user.phone = request.POST['phone']
		#user.addtime = datetime.now()
		#user.save()
		#context = {"info":"insert succeed"}
	#except:
		#context = {"info":"insert failed"}

	#return render(request,"myapp/Users/info.html",context)
	
	'''执行图片的上传'''
	myfile = request.FILES.get("pic",None)
	if not myfile:
		return HttpResponse("没有上传文件信息")
	filename = str(time.time())+"."+myfile.name.split('.').pop()
	destination = open("./static/pics/"+filename,"wb+")
	for chunk in myfile.chunks():      # 分块写入文件  
		destination.write(chunk)  
	destination.close()

	# 执行图片缩放
	im = Image.open("./static/pics/"+filename)
	# 缩放到75*75(缩放后的宽高比例不变):
	im.thumbnail((75, 75))
	# 把缩放后的图像用jpeg格式保存: 
	im.save("./static/pics/s_"+filename,None)

	context = im

	#执行图片删除
	#os.remove("./static/pics/"+filename)
	return HttpResponse("上传成功！图片："+filename)
	


def delUsers(request,uid):

	#return HttpResponse(uid)
	try:
		ob = Users.objects.get(id=uid)
		ob.delete()
		context = {"info":"delete succeed"}
	except:
		context = {"info":"delete failed"}

	return render(request,"myapp/Users/info.html",context)

def editUsers(request,uid):
	try:
		ob = Users.objects.get(id=uid)
		context ={"user":ob }
		return render(request,"myapp/Users/edit.html",context)
	except:
		context = {"info":"没有找到要修改的信息"}

	return render(request,"myapp/Users/info.html",context)

def updateUsers(request):
	try:
		user = Users.objects.get(id=request.POST['id'])
		user.name = request.POST['name']
		user.age = request.POST['age']
		user.phone = request.POST['phone']
		user.save()
		context = {"info":"edit succeed"}
	except:
		context = {"info":"edit failed"}

	return render(request,"myapp/Users/info.html",context)

